package com.csi.controller.user;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.csi.domain.History;
import com.csi.domain.User;
import com.csi.pojo.Result;
import com.csi.service.HistoryService;
import com.csi.service.UserService;
import com.csi.service.impl.HistoryServiceImpl;
import com.csi.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

/**
 * ***钱包转账***
 * 判断是否有支付密码
 * 判断是否达到限额
 * 验证支付密码
 * 判断钱包余额是否足够
 * 判断现在要支付的金额加上今日历史的金额是否超过限额
 * 钱包转账,根据userNumber互转
 * 转账成功生历史记录
 */
@WebServlet("/user/transferByWalletController")
public class TransferByWalletController extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter out = resp.getWriter();

        // 获取请求参数
        String userNumber = req.getParameter("userNumber");
        String targetUserNumber = req.getParameter("targetUserNumber");
        double transferAmount = Double.parseDouble(req.getParameter("transferAmount")); // 转账金额

        // 参数校验
        if (StringUtils.isEmpty(userNumber) || StringUtils.isEmpty(targetUserNumber)) {
            Result result = new Result<>();
            result.setCode(400);
            result.setMsg("请求参数不能为空");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        UserService userService = new UserServiceImpl();
        HistoryService historyService = new HistoryServiceImpl();

        try {

            // 判断userNumber是否为12位
            if (userNumber.length() != 12) {
                Result result = new Result<>();
                result.setCode(400);
                result.setMsg("格式不正确");
                out.print(JSON.toJSONString(result));
                return;
            }

            // 遍历所有用户，查看是否存在该userNumber
            List<User> userList = userService.findAll();
            boolean userExists = false;
            for (User user : userList) {
                if (userNumber.equals(user.getUserNumber())) {
                    userExists = true;
                    break;
                }
            }
            if (!userExists) {
                Result result = new Result<>();
                result.setCode(400);
                result.setMsg("账号不存在");
                out.print(JSON.toJSONString(result));
                return;
            }

            // 判断targetUserNumber是否为12位
            if (targetUserNumber.length() != 12) {
                Result result = new Result<>();
                result.setCode(400);
                result.setMsg("格式不正确");
                out.print(JSON.toJSONString(result));
                return;
            }

            // 遍历所有用户，查看是否存在该targetUserNumber
            boolean targetUserExists = false;
            for (User user : userList) {
                if (targetUserNumber.equals(user.getUserNumber())) {
                    targetUserExists = true;
                    break;
                }
            }
            if (!targetUserExists) {
                Result result = new Result<>();
                result.setCode(400);
                result.setMsg("对方账户不存在");
                out.print(JSON.toJSONString(result));
                return;
            }

            // 判断是否达到限额
            double payLimit = userService.queryPayLimit(userNumber);

            Double todayAmount = historyService.queryTodayAmount(userNumber);

            if (todayAmount >= payLimit) {
                Result result = new Result<>();
                result.setCode(400);
                result.setMsg("今日支付金额已达到限额");
                out.print(JSON.toJSONString(result));
                return;
            }

            // 判断钱包余额是否足够
            double balance = userService.queryBalance(userNumber);
            if (balance < transferAmount) {
                Result result = new Result<>();
                result.setCode(400);
                result.setMsg("钱包余额不足");
                out.print(JSON.toJSONString(result));
                return;
            }

            // 判断现在要支付的金额加上今日历史的金额是否超过限额
            if (todayAmount + transferAmount > payLimit) {
                Result result = new Result<>();
                result.setCode(400);
                result.setMsg("超过今日限额");
                out.print(JSON.toJSONString(result));
                return;
            }

            // 钱包转账,根据userNumber互转
            userService.transferByWallet(userNumber, targetUserNumber, transferAmount);

            // 转账成功生历史记录
            History history = new History();
            history.setUserNumber(userNumber);
            history.setOperationType("转账");
            history.setPayOut(userNumber);
            history.setPayIn(targetUserNumber);
            history.setAmount(transferAmount);
            historyService.add(history);

            Result result = new Result<>();
            result.setCode(200);
            result.setMsg("支付成功");
            out.print(JSON.toJSONString(result));
        } catch (Exception e) {
            Result result = new Result<>();
            result.setCode(500);
            result.setMsg("服务器内部错误");
            out.print(JSON.toJSONString(result));
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }

}
